package com.jamal2362.apktool.fragment.files;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import java.io.File;
import org.json.JSONArray;
import org.json.JSONException;
import com.jamal2362.apktool.MainActivity;
import com.jamal2362.apktool.R;
import com.jamal2362.apktool.fragment.FilesFragment;
import com.jamal2362.apktool.task.CopyTask;
import com.jamal2362.apktool.util.FileUtils;
import com.jamal2362.apktool.util.MUtil;
import com.jamal2362.apktool.util.PopupUtils;
import com.jamal2362.apktool.util.Settings;
import com.jamal2362.apktool.util.TextUtil;
import com.jamal2362.apktool.util.search.Search;
import com.jamal2362.apktool.view.RefreshListView;

public class FilesPager implements View.OnClickListener,View.OnLongClickListener {
	private final View view;
	private final Context ctx;
	private final CharSequence title;
	private RefreshListView files;
	private TextView path;
	private FilesAdapter adapter;
	private String[] storages;
	private ImageView backView;
	private ImageView paste;
	private Search mSearch;
	private ImageView refreshView;

	public FilesPager(Context context) {
		ctx = context;
		LayoutInflater inflater = LayoutInflater.from(context);
		view = inflater.inflate(R.layout.files, null);
		title = context.getText(R.string.files);
		files = view.findViewById(R.id.files);
		refreshView = view.findViewById(R.id.filesImageView1);
		path = view.findViewById(R.id.path);
		path.setTextSize(TypedValue.COMPLEX_UNIT_SP, Settings.appFontSize);
		paste = view.findViewById(R.id.filePaste);
		if (Settings.lightTheme)
			paste.setImageResource(R.drawable.ic_paste_light);
		else
			paste.setImageResource(R.drawable.ic_paste_dark);
		paste.setOnClickListener(this);
		paste.setOnLongClickListener(new OnLongClickListener()
			{
				public boolean onLongClick(View v) {
					TextUtil.st(ctx, ctx.getString(R.string.cancel));
					removeCopyTask();
					adapter.updatePasteView();
					return true;
				}
			});
		path.setOnClickListener(this);
		path.setOnLongClickListener(this);
	}

	public void init(Bundle savedInstanceState, FilesFragment frag) {
		adapter = FilesAdapter.init(frag, files, path);
		adapter.init(savedInstanceState);
		adapter.setPasteView(paste);
		adapter.updatePasteView();
		adapter.setBackView(backView);
		adapter.updateBackView();
		mSearch = new Search(ctx, adapter);
		getStorages();
		final ColorFilter[] filter = new PorterDuffColorFilter[2];
		int drawableColor = (Settings.lightTheme ? Color.DKGRAY : Color.WHITE);
		int accentColor = ContextCompat.getColor(ctx, (R.color.accent_material));
		filter[0] = new PorterDuffColorFilter(accentColor, PorterDuff.Mode.SRC_ATOP);
		filter[1] = new PorterDuffColorFilter(drawableColor, PorterDuff.Mode.SRC_ATOP);
		refreshView.getBackground().setColorFilter(filter[1]);
		refreshView.getBackground().setAlpha(0);
		final float scale = files.getDistance() / 255;
		files.setRefreshListener(new RefreshListView.RefreshListener()
			{
				@Override
				public void onRefresh() {
					adapter.setScrollPosition(path.getText().toString());
					adapter.refresh();
					refreshView.getBackground().setColorFilter(filter[1]);
					refreshView.getBackground().setAlpha(0);
					refreshView.setVisibility(View.GONE);
				}

				@Override
				public void update(final float distance, float refreshDistance) {
					int opacity = Math.round(distance / scale);
					if (opacity > 255) {
						opacity = 255;
					}
					if (opacity <= 255 && opacity >= 10) {
						Drawable refreshDrawable = files.rotateDrawable(refreshView.getBackground(), opacity);
						refreshDrawable.setColorFilter(opacity == 255 ? filter[0] : filter[1]);
						refreshDrawable.setAlpha(opacity);
						refreshView.setBackground(refreshDrawable);
						refreshView.setVisibility(View.VISIBLE);
					} else {
						refreshView.getBackground().setColorFilter(filter[1]);
						refreshView.getBackground().setAlpha(0);
						refreshView.setVisibility(View.GONE);
					}
				}
			});
	}

	public void removeCopyTask() {
		Settings.remove(ctx, "copy_file_path");
		Settings.remove(ctx, "cut_file_mode");
	}

	public void getStorages() {
		storages = FileUtils.getStorages(ctx);
		adapter.setStorages(storages);
	}

	public void save(Bundle outState) {
		adapter.save(outState);
	}

	public CharSequence getTitle() {
		return title;
	}

	public ImageView pasteView() {
		return this.paste;
	}

	public ImageView backView() {
		return this.backView;
	}

	public View getView() {
		return view;
	}

	public FilesAdapter getAdapter() {
		return this.adapter;
	}

	@Override
	public void onClick(View p1) {
		switch (p1.getId()) {
			case R.id.path:
				menu(p1);
				break;

			case R.id.filePaste:
				String target = path.getText().toString();
				if (!target.startsWith(adapter.rootDir.getAbsolutePath()))
					return;
				String sou = Settings.gets(ctx, "copy_file_path", null);
				if (sou == null) {
					TextUtil.st(ctx, ctx.getString(R.string.error));
					removeCopyTask();
					return;
				}
				try {
					JSONArray files = new JSONArray(sou);
					String parent = (String) files.get(0);
					String alertStr = "";
					final File[] source = new File[files.length() - 1];
					for (int i = 1; i < files.length(); i ++) {
						String fpath = parent + "/" + (String) files.get(i);
						if (i > 1)
							alertStr += ", ";
						alertStr += fpath;
						source[i - 1] = new File(fpath);
					}
					boolean cut = Settings.getb(ctx, "cut_file_mode", false);
					final CopyTask ctask = new CopyTask(ctx, target, cut, adapter);
					Runnable r = new Runnable()
					{
						public void run() {
							ctask.execute(source);
							removeCopyTask();
						}
					};
					int confirm = (cut ? R.string.move_here : R.string.copy_here);
					MUtil.createDialog(ctx, ctx.getString(confirm, alertStr), r);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;
		}
	}

	@Override
	public boolean onLongClick(View p1) {
		switch (p1.getId()) {
			case R.id.path:
				adapter.editPath();
				return true;
		}
		return false;
	}

	private void menu(final View view) {
		getStorages();
		final TextView path = (TextView) view;
		final String project = path.getText().toString();
		boolean noRootStr = true;
		final boolean isProject = project.equals(Settings.projectPath);
		//final boolean isExtStorage = (Settings.isKitKat() ? project.startsWith(adapter.rootDir.getAbsolutePath()) : true);

		Menu menu = PopupUtils.show(view, R.menu.dir, new PopupUtils.Callback(){
				@Override
				public void call(Context ctx, int pos) {
					switch (pos) {
						case R.id.go_back:
							adapter.goBack();
							break;

						case R.id.sort:
							sort();
							break;

						case R.id.new_dir:
						case R.id.new_file:
							adapter.createFileOrDir(pos);
							break;

						case R.id.make_home:
							Settings.sets(ctx, "home_dir", project);
							Settings.homeDir = project;
							TextUtil.st(ctx, ctx.getString(R.string.success));
							break;

						case R.id.main_project:
							Settings.setProjectPath((isProject ? "" : project), ctx);
							break;

						case R.id.set_as_output_directory:
							Settings.setOutputDirectory(project, ctx);
							break;

						case R.id.search:
							mSearch.openDialog(project);
							break;

						case R.id.search_res:
							mSearch.resultDialog();
							break;
					}
				}
			});
		if (isProject) {
			menu.findItem(R.id.main_project).setTitle(path.getContext().getString(R.string.close_project));
		}

		final String odir = Settings.output_directory;
		if (odir != null) {
			MenuItem mi = menu.add(0, 1001, 0, path.getContext().getString(R.string.output_directory));
			mi.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
				{
					@Override
					public boolean onMenuItemClick(MenuItem m) {
						File root = new File(odir);
						adapter.refresh(root);
						return true;
					}
				});
		}

		if (storages != null) {
			int i = 0;
			for (; i < storages.length; i++) {
				if (project.equals(storages[i]))
					noRootStr = false;
				MenuItem mi = menu.add(0, (1100 + i), 0, storages[i]);
				mi.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
					{
						@Override
						public boolean onMenuItemClick(MenuItem m) {
							File root = new File(m.getTitle().toString());
							adapter.refresh(root);
							return true;
						}
					});
			}
			MenuItem mi = menu.add(0, (1100 + i), 0, "/system");
			mi.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
				{
					@Override
					public boolean onMenuItemClick(MenuItem m) {
						File root = new File("/system");
						adapter.refresh(root);
						return true;
					}
				});
		}

		File curDir = new File(project);
		File json = new File(project, "apktool.json");
		menu.findItem(R.id.main_project).setVisible(json.exists() && curDir.canWrite());
		menu.findItem(R.id.set_as_output_directory).setVisible(curDir.canWrite());
		menu.findItem(R.id.new_dir).setVisible(curDir.canWrite());
		menu.findItem(R.id.new_file).setVisible(curDir.canWrite());
		menu.findItem(R.id.go_back).setVisible(noRootStr);
		menu.findItem(R.id.search_res).setVisible(!mSearch.isEmpty());
	}

	protected void sort() {
		new AlertDialog.Builder(ctx).
			setTitle(R.string.sort).
			setItems(R.array.sort, new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface p1, int p2) {
					FileComparator.setDefaultAdapter(p2);
					adapter.refresh();
					PreferenceManager.getDefaultSharedPreferences(ctx).
						edit().
						putInt("defaultCompator", p2).
						commit();
				}
			}).
			setCancelable(true).
			show();
	}
}
